package com.beichuan_travel.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Date;

@Slf4j
@Component
public class JwtManager {

    @Value("${security.jwt.secretKey}")
    private String secretKey;

    private Duration expiray = Duration.ofDays(7);

    public String generate(String openid) {
        Date expiration = new Date(System.currentTimeMillis() + expiray.toMillis());

        return Jwts.builder()
                .setExpiration(expiration)   // 过期时间
                .setIssuedAt(new Date())   // 签发时间
                .setSubject(openid)   // 将用户名放入token
                .signWith(SignatureAlgorithm.HS512, secretKey)   // 加密
                .compact();
    }

    public Claims parse(String token) {
        if (!StringUtils.hasLength(token)) {
            return null;
        }

        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (JwtException e) {
            log.error("token失效");
        }
        return claims;
    }

}
